package com.inspireink.project.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/api/python2")
public class PythonScript2Controller {

    private static final Logger logger = LoggerFactory.getLogger(PythonScript2Controller.class);
    @Value("${python.path}")
    private String pythonPath;

    @Value("${scripts.path}")
    private String scriptsPath;

    @Value("${output.path.api2}")
    private String outputPath;

    private final ResourceLoader resourceLoader;

    public PythonScript2Controller(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @PostMapping("/executeApi2")
    public ResponseEntity<String> executeApi2(@RequestParam("clothesImage") MultipartFile clothesImage,
                                              @RequestParam("inspireInkImage") MultipartFile inspireInkImage) {
        try {
            // 保存上传的图片到临时目录
            Path clothesImagePath = saveFile(clothesImage, "clothes.png");
            Path inspireInkImagePath = saveFile(inspireInkImage, "inspire_ink.png");

            // 加载脚本文件、JSON 文件和 mask 文件
            Resource scriptResource = resourceLoader.getResource(scriptsPath + "/api2.py");
            File scriptFile = scriptResource.getFile();
            Resource jsonResource = resourceLoader.getResource(scriptsPath + "/Inspire_Ink_2_API.json");
            File jsonFile = jsonResource.getFile();
            Resource maskResource = resourceLoader.getResource(scriptsPath + "/mask.png");
            File maskFile = maskResource.getFile();

            // 日志记录
            logger.info("Python Path: " + pythonPath);
            logger.info("Script File: " + scriptFile.getAbsolutePath());
            logger.info("Clothes Image Path: " + clothesImagePath.toString());
            logger.info("Inspire Ink Image Path: " + inspireInkImagePath.toString());
            logger.info("Output Path: " + outputPath);
            logger.info("JSON File: " + jsonFile.getAbsolutePath());
            logger.info("Mask File: " + maskFile.getAbsolutePath());


            // 执行 Python 脚本
            ProcessBuilder processBuilder = new ProcessBuilder(pythonPath, scriptFile.getAbsolutePath(),
                    clothesImagePath.toString(), inspireInkImagePath.toString(), outputPath, jsonFile.getAbsolutePath(), maskFile.getAbsolutePath());
            processBuilder.redirectErrorStream(true);
            Process process = processBuilder.start();
            process.waitFor();

            // 读取进程输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder output = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }

            process.waitFor();

            // 日志记录输出
            logger.info("Python script output: " + output.toString());
            // 检查输出文件夹中的生成图像
            File outputDir = new File(outputPath);
            if (outputDir.exists() && outputDir.isDirectory()) {
                File[] outputFiles = outputDir.listFiles();
                if (outputFiles != null && outputFiles.length > 0) {
                    // 返回生成的图像文件名列表
                    StringBuilder result = new StringBuilder("Generated images: ");
                    for (File file : outputFiles) {
                        result.append(file.getName()).append(" ");
                    }
                    return ResponseEntity.ok(result.toString());
                }
            }

            return ResponseEntity.status(500).body("Failed to generate images");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("Error executing Python script: " + e.getMessage());
        }
    }

    private Path saveFile(MultipartFile file, String filename) throws IOException {
        Path filePath = Paths.get(System.getProperty("java.io.tmpdir"), filename);
        file.transferTo(filePath);
        return filePath;
    }
}